package com.wenyu.wenyuyuedu.activity.personage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.homepage.MyAttentionActivity;
import com.wenyu.wenyuyuedu.adapter.personage.MyCollectAdapter;
import com.wenyu.wenyuyuedu.adapter.personage.MyPublicAdapter;
import com.wenyu.wenyuyuedu.bean.homepager.postDeleteBean;
import com.wenyu.wenyuyuedu.bean.personage.MytrendsBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.homepager.postDeleteServer;
import com.wenyu.wenyuyuedu.server.personage.MytrendsServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;
import com.wenyu.wenyuyuedu.view.CircleImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/*
* 我的发表
* */
public class MyPublishActivity extends AppCompatActivity implements View.OnClickListener {
    Toolbar toolbar;
    @InjectView(R.id.tv_mycircle_titlecontent)
    CircleImageView tvMycircleTitlecontent;
    @InjectView(R.id.tv_mycircle_name)
    TextView tvMycircleName;
    @InjectView(R.id.my_detail_left)
    ImageView myDetailLeft;
    @InjectView(R.id.list)
    LRecyclerView recyclerView;
    private Intent intent;
    private Activity activity;
    private String token;
    private int page = 1;
    private MyPublicAdapter adapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private List<MytrendsBean.InfoBean> info;
    private List<MytrendsBean.InfoBean> infoAll = new ArrayList<>();
    private boolean isRefresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_publish);
        StatusBarUtil.setStatusBar(MyPublishActivity.this, R.color.personage_statue);
        ButterKnife.inject(this);
        this.activity = MyPublishActivity.this;
        inivLRcyclerView();
        setupToolbar();
        initView();
        requestData();
    }

    /*初始化recyclerView*/
    private void inivLRcyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        recyclerView.setHasFixedSize(true);
        /*创建adapter对象*/
        adapter = new MyPublicAdapter(activity);
        /*给LRecyclerView的adapter设置adapter*/
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        /*给recyclerView设置adapter*/
        recyclerView.setAdapter(lRecyclerViewAdapter);
        /*下拉刷新*/
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                // adapter.clear();
                //lRecyclerViewAdapter.notifyDataSetChanged();
                isRefresh = true;
                requestData();
            }
        });
        /*加载更多*/
        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (isRefresh) {
                    return;
                }
                page++;
                requestData();
            }
        });
        adapter.setDeleteOnClickLis(new MyCollectAdapter.deleteOnclickListener() {
            @Override
            public void onClick(int position, View view) {
                switch (view.getId()) {
                    /*删除*/
                    case R.id.btn_delete:
                        SwipeMenuLayout parent = (SwipeMenuLayout) view.getParent();
                        parent.quickClose();
                        MytrendsBean.InfoBean infoBean = infoAll.get(position);
                        /*帖子的id*/
                        String id = infoBean.getId();
                        /*登陆的uid*/
                        String uid = infoBean.getUid();
                        deleteInvitation(position, id, uid);
                        break;
                    /*条目的点击事件*/
                    case R.id.tv:
                        intent.setClass(activity, MyAttentionActivity.class);
                        String invitationId = infoAll.get(position).getId();
                        String title = infoAll.get(position).getTitle();
                        intent.putExtra("allattentionnickname", tvMycircleName.getText());
                        intent.putExtra("allattentionid", invitationId);
                        intent.putExtra("allattentiontitle", title);
                        startActivity(intent);
                        break;
                }
            }
        });
        recyclerView.setFooterViewHint("正在加载中...", "没有更多数据了", "网络请求失败");
        recyclerView.setFooterViewColor(R.color.footview_text_color,R.color.footview_text_color,R.color.footview_back);
    }

    /*删除帖子*/
    private void deleteInvitation(final int position, String id, String uid) {
        postDeleteServer postDeleteServer = ApiWrapper.getInstance().create(postDeleteServer.class);
        Call<postDeleteBean> delete = postDeleteServer.getDelete(token, id, uid);
        delete.enqueue(new Callback<postDeleteBean>() {
            @Override
            public void onResponse(Call<postDeleteBean> call, Response<postDeleteBean> response) {
                postDeleteBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    String msg = body.getMsg();
                    if (code == 1) {
                        MyToast.showToast(activity, "删除成功", Toast.LENGTH_SHORT);
                        adapter.getList().remove(position);
                        adapter.notifyDataSetChanged();
                    } else if (code == 0) {
                        showLoginDoalog();
                    } else if (code == 2800) {
                        MyToast.showToast(activity, msg, Toast.LENGTH_SHORT);
                    } else if (code == 2801) {
                        MyToast.showToast(activity, msg, Toast.LENGTH_SHORT);
                    } else if (code == 2802) {
                        MyToast.showToast(activity, msg, Toast.LENGTH_SHORT);
                    } else if (code == 2803) {
                        MyToast.showToast(activity, msg, Toast.LENGTH_SHORT);
                    } else if (code == 2804) {
                        MyToast.showToast(activity, msg, Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<postDeleteBean> call, Throwable t) {
                MyToast.showToast(activity, "网络异常，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });

    }


    /*获取发表的态*/
    private void requestData() {
        token = AbSharedUtil.getString(activity, SharedConstants.USER_TOKEN);
        MytrendsServer mytrendsServer = ApiWrapper.getInstance().create(MytrendsServer.class);
        Call<MytrendsBean> mytrends = mytrendsServer.getMytrends(token, page);
        mytrends.enqueue(new Callback<MytrendsBean>() {
            @Override
            public void onResponse(Call<MytrendsBean> call, Response<MytrendsBean> response) {
                MytrendsBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    String msg = body.getMsg();
                    if (code == 1) {
                        /*头像*/
                        Glide.with(activity)
                                .load(body.getUserIcon())
                                .error(R.drawable.login_logo)
                                .into(tvMycircleTitlecontent);
                        /*昵称*/
                        tvMycircleName.setText(body.getNickname());
                        info = body.getInfo();
                        if (info.size() == 0) {
                            MyToast.showToast(activity, "没有相关的数据！", Toast.LENGTH_SHORT);
                        } else {
                            if (isRefresh) {
                                //下拉刷新
                                adapter.clear();
                            }
                            isRefresh = false;
                            infoAll.addAll(info);
                            adapter.addAll(info);
                            lRecyclerViewAdapter.notifyDataSetChanged();
                        }
                    } else if (code == 0) {
                        //token错误
                        showLoginDoalog();
                    } else if (code == 5000) {
                        //登陆后操作
                        showLoginDoalog();
                    }
                    recyclerView.refreshComplete(page);
                }
            }

            @Override
            public void onFailure(Call<MytrendsBean> call, Throwable t) {
                netError();
                MyToast.showToast(activity, "网络异常，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }

    /**
     * 网路请求失败时的操作
     */
    private void netError() {
        isRefresh = false;
        recyclerView.refreshComplete(page);
        recyclerView.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
            @Override
            public void reload() {
                requestData();
            }
        });
    }

    /*显示是否删除帖子的dialog*/
    private Dialog deleteAd;
    private TextView deleteQuxiao;
    private TextView deleteQueding;

    private void deleteDoalog() {
        deleteAd = new android.app.AlertDialog.Builder(activity).create();
        deleteAd.show();
        Window window = deleteAd.getWindow();
        window.setContentView(R.layout.dailog_login);
        deleteQuxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        deleteQueding = (TextView) window.findViewById(R.id.dialog_login_queding);
        deleteQuxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteAd.dismiss();
            }
        });
        deleteQueding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyToast.showToast(activity, "删除功能暂未实现", Toast.LENGTH_SHORT);
                deleteAd.dismiss();
            }
        });
    }

    /*显示登陆的dialog*/
    private Dialog ad;
    private TextView quxiao;
    private TextView queding;

    private void showLoginDoalog() {
        ad = new android.app.AlertDialog.Builder(activity).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbSharedUtil.putString(activity, SharedConstants.USER_TOKEN, "");
                Intent intent = new Intent();
                intent.setClass(activity, LoginActivity.class);
                startActivity(intent);
                finish();
                ad.dismiss();
            }
        });
    }

    /*初始化控件*/
    private void initView() {
        intent = new Intent();
        myDetailLeft.setOnClickListener(this);

    }

    /*初始化toolbar*/
    private void setupToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*返回*/
            case R.id.my_detail_left:
                finish();
                break;
        }
    }
}
